﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.IO;

namespace Landscape.Members {
    /// <summary>
    /// Represents an XPath inline expression
    /// </summary>
    public class InlineExpression {
        private XPathDocument _DataSource;

        /// <summary>
        /// Data source used by the transformation
        /// </summary>
        public object DataSource {
            get {
                return _DataSource;
            }
            set{
                Renderer.LoadXPathDocument(value, out _DataSource);
            }
        }
        /// <summary>
        /// The expression to compile
        /// </summary>
        public string XPath {
            get;
            set;
        }

        /// <summary>
        /// Wether to disable escaping of expression's output
        /// </summary>
        public bool DisableOutputEscaping {
            get;
            set;
        }

        /// <summary>
        /// The output method of this expression
        /// </summary>
        public OutputMethods OutputMethod {
            get;
            set;
        }

        /// <summary>
        /// Performs compilation of this inline expression
        /// </summary>
        /// <returns>The result of compilation</returns>
        public string Compile() {
            OutputMethods rawMethod = OutputMethod == OutputMethods.xhtml ? OutputMethods.xml : OutputMethod;
            string template = Landscape.Resources.GetEmbeddedResource("Landscape.Templates.InlineXPath.xslt");
            template = string.Format(template,
                                     rawMethod.ToString().ToLower(),
                                     XPath,
                                     DisableOutputEscaping? "yes": "no");
            XmlDocument stylesheet = new XmlDocument();
            stylesheet.LoadXml(template);

            XslCompiledTransform compiled = new XslCompiledTransform();

            compiled.Load(stylesheet, new XsltSettings(true, true), new TemplateXmlUrlResolver(Context.Instance.includePaths));

            string result = null;

            using (Stream ms = Context.Instance.compiler.Transform(this._DataSource, compiled, null)) {
                using (StreamReader sr = new StreamReader(ms)) {
                    result = sr.ReadToEnd();
                }
            }
            return result;
        }
    }
}
